package net.csdra.libraryborrowing.service.book;

import net.csdra.libraryborrowing.domain.book.BookInfo;
import net.csdra.libraryborrowing.domain.book.BookStorageBox;
import net.csdra.libraryborrowing.domain.book.BookStorageBoxRepository;
import net.csdra.libraryborrowing.service.user.CurrentUserInfo;
import net.csdra.libraryborrowing.util.Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.nio.file.AccessDeniedException;
import java.util.List;

/**
 * Created by xiaomi on 2017/10/17.
 */
@Service
public class BookStorageBoxServiceImpl implements BookStorageBoxService {

    @Autowired
    BookStorageBoxRepository bookStorageBoxRepository;
    @Autowired
    CurrentUserInfo currentUserInfo;
    @Autowired
    BookInfoComponent bookInfoComponent;

    @Override
    public BookStorageBox putBookInfo(PutBookInfo putBookInfo) throws AccessDeniedException {
        BookInfo bookInfo = bookInfoComponent.getBookInfoById(new BookInfoComponent.GetBookInfoById(putBookInfo.getBookInfoId()));
        Assert.notNull(bookInfo, "@找不到此书！");
        List<BookStorageBox> bookStorageBoxList = bookStorageBoxRepository.findByMetaId(currentUserInfo.get().getId());
        Assert.isTrue(bookStorageBoxList.size() < 100, "@书籍收藏数量已达上限！");
        for (int i = 0; i < bookStorageBoxList.size(); i++) {
            Assert.isTrue(!bookInfo.getId().equals(bookStorageBoxList.get(i).getBookInfoId()), "@您已收藏过此书！");
        }
        BookStorageBox returnValue = new BookStorageBox();
        BookStorageBox bookStorageBox = Utils.createAutoSet(BookStorageBox.class, currentUserInfo.get().getUserName());
        bookStorageBox.setBookInfoId(putBookInfo.getBookInfoId());
        bookStorageBox.setMetaId(currentUserInfo.get().getId());
        bookStorageBoxRepository.save(bookStorageBox);
        BeanUtils.copyProperties(bookStorageBox, returnValue);
        return returnValue;
    }

    @Override
    public boolean removeBookStrorageBook(RemoveBookStrorageBook removeBookStrorageBook) throws AccessDeniedException {
        Assert.notNull(removeBookStrorageBook.getBookInfoId(), "参数为空！");
        List<BookStorageBox> bookStorageBoxList = bookStorageBoxRepository.findByMetaId(currentUserInfo.get().getId());
        for (int i = 0; i < bookStorageBoxList.size(); i++) {
            if (removeBookStrorageBook.getBookInfoId().equals(bookStorageBoxList.get(i).getBookInfoId())){
                bookStorageBoxRepository.delete(bookStorageBoxList.get(i).getId());
                break;
            }
        }
        return true;
    }
}
